package com.driver.utils;

import com.alibaba.fastjson2.JSONObject;
import com.driver.pojo.entity.Temperature;
import com.driver.service.IConfigService;
import com.driver.service.ITemperatureService;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;

/**
 * 串口通信工具类
 */
@Slf4j
@Component
public class CommUtils implements SerialPortEventListener {

    @Autowired
    private ITemperatureService temperatureService;
    @Autowired
    private IConfigService configService;

    private static final String PORT_NAME = "COM4";
    private static final int BIT_RATE = 11500;
    public static final int DATA_BITS = SerialPort.DATABITS_8;
    public static final int STOP_BIT = SerialPort.STOPBITS_1;
    public static final int PARITY_BIT = SerialPort.PARITY_NONE;

    private static SerialPort serialPort;
    private static InputStream in;
    private static OutputStream out;
    private static CommUtils commUtils;

    private CommUtils() {
    }

    public static CommUtils getInstance() {
        if (commUtils == null) {
            commUtils = new CommUtils();
            commUtils.init();
        }
        return commUtils;
    }

    /**
     * 初始化串口
     * 根据端口名称获取端口对象
     * 判断对象是否被占用
     * 判断端口类型，其中1代表串口，如果是串口就打开串口，设置设备参数，设置输入输出流，以及设置数据监听
     */
    public void init() {
        try {
            CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(PORT_NAME);
            if (portIdentifier.isCurrentlyOwned()) {
                System.out.println("Error: Port is currently in use");
            } else if (portIdentifier.getPortType() == 1) {
                serialPort = (SerialPort) portIdentifier.open(PORT_NAME, 1000);
                serialPort.setSerialPortParams(BIT_RATE, DATA_BITS, STOP_BIT, PARITY_BIT);

                in = serialPort.getInputStream();
                out = serialPort.getOutputStream();

                serialPort.addEventListener(this);
                serialPort.notifyOnDataAvailable(true);
            } else {
                System.out.println("Error: Only serial ports are handled by this example.");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void send(String message) {
        try {
            byte[] bytes = hexStrToByteArray(message);
            out.write(bytes);
            Thread.sleep(1000);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * serialEvent函数，大概就是用来监听事件，他包括很多事件，但是我只判断一个，是否有是可用数据，如果存在可用数据就接收
     * @param event
     */
    public void serialEvent(SerialPortEvent event) {
        switch (event.getEventType()) {
            case SerialPortEvent.DATA_AVAILABLE:
                String receive = receive();
                saveReceiveData(receive);
                log.info("接收到数据：{}", receive);
                break;
        }
    }
    public void saveReceiveData(String receive) {
        JSONObject jsonObject = JSONObject.parseObject(receive);
        Temperature temperature = new Temperature();
        temperature.setCode(configService.getCode());
        if (jsonObject.containsKey("time")) {
            temperature.setMonitorTime(Instant.ofEpochSecond(jsonObject.getLong("time")).atZone(ZoneId.systemDefault()).toLocalDateTime());
        } else {
            temperature.setMonitorTime(LocalDateTime.now());
        }
        temperature.setJTemp(jsonObject.getDouble("temp"));
        temperature.setSTemp(jsonObject.getDouble("temp"));
        temperature.setVoltage(configService.getVoltage());
        temperature.setRate(configService.getRate());
        temperature.setCode(configService.getCode());
        temperatureService.save(temperature);
    }

    /**
     * receive函数，用来接收收到的数据，这里比较好理解，通过上面初始化的输入流，将获取到的数据存入byte数组，并且将其转成字符串返回
     * @return
     */
    public String receive() {
        byte[] buffer = new byte[128];
        int data;
        String result = null;
        try {
            int len = 0;
            while ((data = in.read()) > -1) {
                buffer[len++] = (byte) data;
            }
            byte[] copyValue = new byte[len];
            System.arraycopy(buffer, 0, copyValue, 0, len);
            result = ByteArrayToString(copyValue);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * send函数，send函数将要发送的16进制字符串消息转换成byte数组发送，并且让线程休眠1秒
     */
    public void close() {
        try {
            in.close();
            out.close();
            serialPort.notifyOnDataAvailable(false);
            serialPort.removeEventListener();
            serialPort.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //16进制转byte数组
    public byte[] hexStrToByteArray(String str) {
        if (str == null) {
            return null;
        }
        if (str.length() == 0) {
            return new byte[0];
        }
        byte[] byteArray = new byte[str.length() / 2];
        for (int i = 0; i < byteArray.length; i++) {
            String subStr = str.substring(2 * i, 2 * i + 2);
            byteArray[i] = ((byte) Integer.parseInt(subStr, 16));
        }
        return byteArray;
    }

    public String ByteArrayToString(byte[] by) {
        String str = "";
        for (int i = 0; i < by.length; i++) {
            String hex = Integer.toHexString(by[i] & 0xFF);
            if (hex.length() == 1) {
                hex = "0" + hex;
            }
            str += hex.toUpperCase();
        }
        return str;
    }

    public static void main(String[] args) {
        CommUtils commUtil = CommUtils.getInstance();
    }
}
